package com.express.basic.token;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.express.basic.constant.ExpressConstant;


@Service
public class DefaultTokenManager implements TokenManager{
	
	
	@Autowired
	private RedisTemplate<String,String> stringRedisTemplate;
	
	
    @Override
    public String createToken(Integer userId) {
        String token = UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(ExpressConstant.TOKEN+token, userId+"", 24, TimeUnit.HOURS);
        
        return token;
    }

    @Override
    public boolean checkToken(String token) {
    	if(StringUtils.isBlank(token))
    		return false;
    	return stringRedisTemplate.hasKey(ExpressConstant.TOKEN+token);
    }

	@Override
	public Integer getUserId(String token) {
		return Integer.valueOf(stringRedisTemplate.opsForValue().get(ExpressConstant.TOKEN+token));
	}

	@Override
	public void refreshToken(String token) {
		stringRedisTemplate.expire(ExpressConstant.TOKEN+token, 24, TimeUnit.HOURS);
	}

	@Override
	public void removeToken(String token) {
		stringRedisTemplate.delete(ExpressConstant.TOKEN+token);
	}

	
}
